<script setup lang="ts">
import { type Props } from "@/types/index.ts";
import { createNode, setYogaStyle } from "@/utils/calculate.ts";
import generateUUIDv4 from "@/utils/uuid.ts";
import {
  provide,
  inject,
  ref,
  onBeforeUnmount,
  getCurrentInstance,
  watch
} from "vue";
import { nodeRegistry } from "@/utils/layoutNodeRegistry.ts";
import { redrawByPropsUpdate } from "@/utils/propsTracker.ts";

const id = generateUUIDv4(); // 为每个实例生成唯一ID

const props = withDefaults(defineProps<Props>(), {
  id: "", // 移除默认值中的 generateUUIDv4()
  width: 50,
  height: 50
});

// 使用实例生成的ID创建节点
let currentNode = createNode({
  ...props,
  id: id // 使用实例的唯一ID
}).node;
const instance = getCurrentInstance();
const parent = instance.parent.exposed.getNode();

if (parent) {
  const child = currentNode;

  if (child) {
    parent.insertChild(child, parent.getChildCount());
    nodeRegistry.add(id);
  }
}
onBeforeUnmount(() => {
  if (parent && currentNode) {
    // 从父节点中移除当前的 Yoga 节点
    parent.removeChild(currentNode);
    // 从注册表中移除节点 ID
    nodeRegistry.remove(id);
  }
});
defineExpose({
  getNode: () => {
    return currentNode;
  }
});

// 监听 props 变化
// 分别监听需要的属性
Object.keys(props).forEach(key => {
  watch(
    () => props[key],
    (newVal, oldVal) => {
      console.log(`${key} 发生变化:`, newVal, oldVal);
      
      if (currentNode && newVal !== oldVal) {
        const hasChangedProps = { [key]: newVal };
        setYogaStyle(hasChangedProps, currentNode);
        redrawByPropsUpdate();
      }
    }
  );
});
</script>

<template>
  <slot />
</template>
